<?php

namespace App\Http\Controllers\Admin;
use App\DTOS\Admin\ServerGroupDTO;
use App\Http\Controllers\Controller;
use App\Models\Game\ConfigGroup;
use App\Services\Game\ServerGroupService;
use App\Utils\ResponseUtil;
// 服务器分组列表
class ServerGroupController extends Controller
{
    private ServerGroupService $ServerGroupService;

    /**
     * ServerGroupController constructor.
     * @param ServerGroupService $ServerGroupService
     */
    public function __construct(ServerGroupService $ServerGroupService)
    {
        $this->ServerGroupService = $ServerGroupService;
    }

    public function paginate()
    {
        // 获取分页数据
        $paginate = $this->ServerGroupService->paginate(new ServerGroupDTO(request()->all()));

        // 将 items 转换为集合
        $items = collect($paginate->items());

        // 提取所有类型
        $types = $items->pluck('type')->unique();

        // 批量查询 ConfigGroup 数据
        $configGroups = ConfigGroup::query()->whereIn('id', $types)->get()->keyBy('id');

        // 处理每个分页项，添加 ConfigGroup 数据
        $data = $items->map(function ($item) use ($configGroups) {
            // 将 ConfigGroup 数据合并到原始数据中
            $item->configs = isset($configGroups[$item->type]) ? $configGroups[$item->type] : null;
            return $item;
        });

        // 准备响应数据
        $res = [];
        $res['code'] = 0;
        $res['msg'] = 'success';
        $res['data'] = $data;
        $res['count'] = $paginate->total();

        return ResponseUtil::json($res);
    }
    public function hvpaginate()
    {
        $paginate = $this->ServerGroupService->paginate(new ServerGroupDTO(request()->all()));

        $res = [];
        $res['code'] = 0;
        $res['msg'] = 'success';
        $res['data'] = $paginate->items();
        $res['count'] = $paginate->total();
        return ResponseUtil::json($res);
    }

    public function add()
    {
        $data = request()->all();
        $result = $this->ServerGroupService->add($data);

        if ($result === false) {
            return ResponseUtil::error('Type already exists', 400); // 返回错误信息和状态码
        }

        return ResponseUtil::success($result); // 返回插入的记录
    }
    public function edit($id)
    {
        $data = request()->all();
        $result =  $this->ServerGroupService->edit($id,$data);

        if ($result === false) {
            return ResponseUtil::error('更新失败', 400); // 返回错误信息和状态码
        }
        return ResponseUtil::success($result);
    }
    public function detail($id)
    {
        $data = $this->ServerGroupService->detail($id);

        return ResponseUtil::success($data);
    }
    public function delete($id)
    {
        $this->ServerGroupService->delete($id);
        return ResponseUtil::success();
    }
}
